
const Metalsmith = require('metalsmith');
const ora = require('ora');
const Handlebars = require('handlebars')
const path = require('path')
const fs = require('fs')
const { projectSucceess,projectFailed } = require('./log')

module.exports = function (data) {
  const spinner = ora({ color: 'yellow', text: 'Building projects...' });
  spinner.start();
return new Promise((resolve,reject)=>{
  const metalsmith = Metalsmith(process.cwd())
    .metadata(data) // 源数据
    .clean(false)
    .ignore(['.umi', 'node_modules'])
    .source(data.tempName) // 源目录
    .destination(data.projectRoot); //目标目录

  const ignoreFile = path.join(data.tempName, 'templates.ignore');
  if (fs.existsSync(ignoreFile)) {
    metalsmith.use((files, metalsmith, done) => {
      const meta = metalsmith.metadata();
      const ignores = Handlebars.compile(fs.readFileSync(ignoreFile).toString())(meta)
        .split('\n').filter(item => !!item.length);

      Object.keys(files).forEach(fileName => {
        // 移除被忽略的文件及文件夹
        ignores.forEach(ignorePattern => {
          if (fileName.indexOf(ignorePattern) >= 0) {
            delete files[fileName];
          }
        })
      })
      done();
    })
  }

  metalsmith.use((files, metalsmith, done) => {
    const meta = metalsmith.metadata();

    Object.keys(files).forEach(fileName => {
      // 解析ds文件报错
      if (fileName !== '.DS_Store' && fileName) {
        const t = files[fileName].contents.toString()
        const template = Handlebars.compile(t)
        files[fileName].contents = Buffer.from(template(meta));

      }
    })
    done();
  }).build(err => {
    if (err) {
      spinner.fail(projectFailed(data.projectName));
      console.log('err',err)
      reject()
    } else {
      resolve()
      spinner.succeed(projectSucceess(data.projectName));
    }
  });
})
}